#!/bin/bash

BOXNAME='jboss'
WORKSTATION='cgreene.teleflora.org'

vagrant_dir="/vagrant"
vagrant_lock_file="${vagrant_dir}/lock_file"

### Add EPEL Repo to server
sudo rpm -i http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm

### Change hostname
sudo hostname "$BOXNAME-$WORKSTATION"
sed -i "s/centos64baseCLI/$BOXNAME-$WORKSTATION/" /etc/sysconfig/network
sudo bash -c 'echo "127.0.0.1   `hostname`" >> /etc/hosts'

if [ -d $vagrant_dir ]; then 
	touch $vagrant_lock_file
fi

### Install all packages need for bootstrap
required_pkgs='zip unzip java-1.6.0-openjdk ant'
for pkg in $required_pkgs; do
	sudo yum -y install $pkg
done

yum_output=`sudo yum -y update | grep 'No Packages marked for Update'`
echo $yum_output
if [ -z "$yum_output" ]; then
	sudo reboot
fi 

DOWNLOAD_DIR='/usr/src'
JBOSS_VERSION=5.1.0
JBOSS_FILE="jboss-${JBOSS_VERSION}"
JBOSS_ZIPFILE="jboss-${JBOSS_VERSION}.GA.zip"
JBOSS_FULL_ZIPFILE="${DOWNLOAD_DIR}/${JBOSS_ZIPFILE}"
JBOSS_INIT="/etc/init.d/jboss"


jboss_install(){
	echo "Installing Jboss $JBOSS_VERSION"
	sudo unzip ${JBOSS_FULL_ZIPFILE} -d /opt/
	sudo mv /opt/${JBOSS_FILE}.GA /opt/${JBOSS_FILE}

	echo "Creating JBoss User"
	sudo useradd -r -d /opt/${JBOSS_FILE} jboss

	echo "Changing permissions of /opt/${JBOSS_FILE}"
	sudo chown -R jboss.jboss /opt/${JBOSS_FILE}

	echo "Setting Environment Variables"
	export JBOSS_HOME=/opt/${JBOSS_FILE}
	export JAVA_HOME=/usr/lib/jvm/jre-openjdk	
	export PATH=$PATH:$JAVA_HOME/bin

	echo "Copy jboss init"
	cp $JBOSS_HOME/bin/jboss_init_redhat.sh $JBOSS_INIT

	echo "Edit jboss init script"
	
	sudo sed -i "s/\/usr\/local\/jboss/\/opt\/${JBOSS_FILE}/g" $JBOSS_INIT 
	sudo sed -i 's/\/usr\/local\/jdk\/bin/\/usr\/lib\/jvm\/jre-openjdk\/bin/g' $JBOSS_INIT 
	sudo sed -i 's/+\"-b $JBOSS_HOST\"/-\"-b 0.0.0.0\"/g' $JBOSS_INIT 

}

jboss_start(){
	if [ -f $JBOSS_INIT ]; then
		echo "Starting JBoss"
		sudo $JBOSS_INIT start
	fi
}

if [ -f ${JBOSS_FULL_ZIPFILE} ]; then
	echo "$JBOSS_FILE exits" 
else
	wget --quiet -P $DOWNLOAD_DIR http://sourceforge.net/projects/jboss/files/JBoss/JBoss-${JBOSS_VERSION}.GA/${JBOSS_ZIPFILE}/download?use_mirror=softlayer-dal 
	jboss_install
	jboss_start
fi

